/**
 *Copyright (c) 2024 watereyes
 * workflow is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.workflow.api.listener;

import java.util.Collection;
import java.util.List;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.EngineServices;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 流程创建监听事件
 * @author bin
 *
 */
public class ProcessCreatedListener extends ProcessListenerAdapter{
	
	private static Logger log = LoggerFactory.getLogger(ProcessCreatedListener.class);
	
	@Override
	public void processCreated(ActivitiEvent event) {
		log.info("流程已经创建.....");
		EngineServices engineService = event.getEngineServices();
		RepositoryService repositoryService = engineService.getRepositoryService();
		RuntimeService runtimeService = engineService.getRuntimeService();
		BpmnModel model = repositoryService.getBpmnModel(event.getProcessDefinitionId());
		Collection<FlowElement> flowElements = model.getProcesses().get(0).getFlowElements();
		// 把每个节点配置的人员信息报错到流程变量里面去
		for (FlowElement one : flowElements) {
            if (one instanceof UserTask) {
                List<String> candidateUsers = ((UserTask) one).getCandidateUsers();
                if(candidateUsers != null && candidateUsers.size() > 0) {
                	 runtimeService.setVariable(event.getExecutionId(), one.getId().replaceAll("-", "") + "_User", candidateUsers);
                }
            }
        }
	}
}
